package com.paishen.common.okhttp;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.ResponseBody;

import java.io.IOException;

import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * https://github.com/lizhangqu/CoreProgress
 */
public class OkProgressResponseBody extends ResponseBody {
	private final ResponseBody responseBody;
	private final OkCallbackAdapter<?> okCallbackAdapter;
	private BufferedSource bufferedSource;

	public OkProgressResponseBody(ResponseBody responseBody, OkCallbackAdapter<?> okCallbackAdapter) {
		this.responseBody = responseBody;
		this.okCallbackAdapter = okCallbackAdapter;
	}

	@Override
	public MediaType contentType() {
		return responseBody.contentType();
	}

	@Override
	public long contentLength() throws IOException {
		return responseBody.contentLength();
	}

	@Override
	public BufferedSource source() throws IOException {
		if (bufferedSource == null) {
			// 包装
			bufferedSource = Okio.buffer(source(responseBody.source()));
		}
		return bufferedSource;
	}

	private Source source(Source source) {
		return new ForwardingSource(source) {
			// 当前读取字节数
			long totalBytesRead = 0L;

			@Override
			public long read(Buffer sink, long byteCount) throws IOException {
				long bytesRead = super.read(sink, byteCount);
				// 增加当前读取的字节数，如果读取完成了bytesRead会返回-1
				totalBytesRead += bytesRead != -1 ? bytesRead : 0;
				// 回调，如果contentLength()不知道长度，会返回-1
				if (okCallbackAdapter != null) {
					okCallbackAdapter.onProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
				}
				return bytesRead;
			}
		};
	}
}